<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>D站</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="keywords" content="">
    <link rel="icon" th:href="@{/pagesResource/img/icon.png}">
    <link rel="stylesheet" type="text/css" th:href="@{/pagesResource/css/animate.css}">
    <link rel="stylesheet" type="text/css" th:href="@{/pagesResource/css/bootstrap.min.css}">
    <link rel="stylesheet" type="text/css" th:href="@{/pagesResource/css/iconfont.css}">
    <link rel="stylesheet" type="text/css" th:href="@{/pagesResource/css/style.css}">
    <link rel="stylesheet" type="text/css" th:href="@{/pagesResource/css/responsive.css}">
    <link rel="stylesheet" type="text/css" th:href="@{/pagesResource/css/color.css}">
    <script th:src="@{/js/sweetAlert.js}"></script>
</head>
<body>
<div class="wrapper hp_1">
    <!-- 引入头部 -->
    <div th:include="main/simpleHeader :: header"></div>
</div>
<section class="dyn-container">
    <div class="container" style="max-width: 1170px;">
        <div class="dyn-main">
            <div class="dyn-check-banner">
                <div class="dyn-update-banner">
                    <h1 class="main-banner-issue">
                        <h1>编辑动态</h1>
                        <form action="" method="post" id="updateDynamicForm" role="form" enctype="multipart/form-data">
                            <div class="dyn-update-form">
                                <div class="dyn-update-frame">
                                    <textarea name="textfield1" class="Size" id="dyn-content" rows="4"
                                              maxlength="500" th:text="${dynamic.dynamicContent}"/>
                                </div>
                                <!--发布动态框下按钮组-->
                                <div class="dyn-update-buttons">
                                    <div class="top-issue-buttons-left">
                                        <!--图片上传-->
                                        <span class="iconfont icon-img" id="dynImgUpload"></span>
                                        <input name="file" id="topIssueImages" type="file" accept="image/*"
                                               multiple="multiple" style="display:none">
                                    </div>
                                </div>
                                <div class="dyn-images">
                                    <div class="dyn-img" th:each="image:${dynamic.images}">
                                        <img class="" th:src="@{/images/dynImages/{image}(image=${image})}" th:alt="${image}">
                                        <button class="dyn-img-btn">X</button>
                                    </div>
                                </div>
                                <div class="dyn-buttons">
                                    <input type="button" class="btn btn-warning" name="button1" id="updateDynamic" value="保存"
                                           onclick="submitState()"/>
                                    <input type="button" class="btn btn-danger" name="button1" value="取消" onclick="returnHome()"/>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

            </div>

        </div>
    </div>
</section>
<script th:src="@{/pagesResource/js/jquery.min.js}"></script>
<script th:src="@{/pagesResource/js/bootstrap.min.js}"></script>
<!--<script th:src="@{/pagesResource/js/CustomerIndex.js}"></script>-->
<script th:src="@{/pagesResource/js/trim.js}"></script>
<script th:src="@{/pagesResource/js/script.js}"></script>
<script type="text/javascript">
    Array.prototype.indexOf = function (val) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == val) return i;
        }
        return -1;
    };
    Array.prototype.remove = function (val) {
        var index = this.indexOf(val);
        if (index > -1) {
            this.splice(index, 1);
        }
    };
    var uploadImg = [];//上传动态图片
    var dynImage = [];//原来动态图片
    $(document).ready(function() {
        var images = $('.dyn-images img').toArray();
        for (let i=0;i<images.length;i++){
            dynImage[i] = images[i].getAttribute("alt");
        }
        console.log("dynImage:"+dynImage);
    });
    $(document).on("click", "#dynImgUpload", function () {
        // 点击图片的同时，点击上传文件的input
        $('#topIssueImages').click();
    });
    // 将上传的图片显示到页面上
    $(document).on("change", "#topIssueImages", function () {
        var fileDom = document.getElementById("topIssueImages");
        //获取选择的图片文件
        var fileList = fileDom.files;
        for (var i = 0; i < fileList.length; i++) {
            if ((uploadImg.length+dynImage.length) > 3) {
                swal("警告", "只能上传4张图片", "warning");
                break;
            }
            if (checkFile(fileList[i])) {
                uploadImg.push(fileList[i]);
                readFile(fileList[i]);
            }
        }
        console.log("uploadImg:"+uploadImg);
        var file = $('#topIssueImages');
        file.after(file.clone().val(""));
        file.remove();
    });
    $(".dyn-images .dyn-img-btn").click(function (e) {
        var $btn = $(e.target);
        var $divimg = $btn.parent();
        var $img = $divimg.children('img');
        var imgname = $img.attr("alt");
        for (var i = 0; i < uploadImg.length; i++) {
            if (imgname === uploadImg[i].name) {
                uploadImg.remove(uploadImg[i]);
                break;
            }
        }
        for (var i = 0; i < dynImage.length; i++) {
            if (imgname === dynImage[i]) {
                dynImage.remove(dynImage[i]);
                break;
            }
        }
        console.log("uploadImg:"+uploadImg);
        console.log("dynImage:"+dynImage);
        $divimg.remove();
    });

    function checkFile(file) {
        //取得上传文件的类型file.files[0].type
        var fileType = file.type.split("/")[0]; //
        //取得上传文件的后缀名
        var fileExt = file.name.split(".")[1];
        //取得上传文件的文件名
        var fileName = file.name.split(".")[0];
        //取得上传文件的大小
        var fileSize = file.size;
        //允许上传类型正则
        var pattern = /^(jpg|png|gif|JPG|PNG|GIF)$/;
        //文件大小判断
        if (parseInt(fileSize) > (5 * 1024 * 1024)) {
            swal("错误", "文件大小不能超过5MB！", "error");
            return false;
        }
        //是否是图片
        if (!(fileType == "image")) {
            swal("错误1", "只允许上传这些格式的图片(jpg|png|gif|JPG|PNG|GIF)", "error");
            return false;
        }
        //进行后缀名匹配
        if (!pattern.test(fileExt)) {
            //设置提醒错误内容
            swal("错误2", "只允许上传这些格式的图片(jpg|png|gif|JPG|PNG|GIF)", "error");
            //将组件设置为空
            return false;
        }
        //匹配成功，上传预览
        if (!file) {
            swal("错误", "浏览器不支持文件上传，请升级浏览器版本或者更换浏览器！", "error");
            return false;
        }
        for (var i = 0;i < dynImage.length; i++){
            if (fileName == dynImage[i]){
                swal("警告", "已经存在该图片，无需重复上传", "warning");
                return false;
            }
        }
        return true;
    }

    function readFile(file) {
        //判断是否支持FileReader
        if (window.FileReader) {
            var reader = new FileReader();
        } else {
            alert("您的浏览器不支持图片预览功能，如需该功能请升级您的浏览器！");
        }
        //获取图片dom
        var $div = $('<div class="dyn-img"></div>');
        var $img = $('<img>');
        var $deleteButton = $('<button class="dyn-img-btn">X</button>');
        // $deleteButton.attr("onclick","deleteImg("+file.name+")");
        $deleteButton.bind("click", function (e) {
            var $btn = $(e.target);
            var $divimg = $btn.parent();
            var $img = $divimg.children('img');
            var imgname = $img.attr("alt");
            for (var i = 0; i < uploadImg.length; i++) {
                if (imgname == uploadImg[i].name) {
                    uploadImg.remove(uploadImg[i]);
                    break;
                }
            }
            console.log("uploadImg:"+uploadImg);
            $divimg.remove();
        });
        reader.readAsDataURL(file);
        reader.onload = function (e) {
            //图片路径设置为读取的图片
            $img.attr('src', e.target.result);
        };
        $img.attr('alt', file.name);
        $div.append($img);
        $div.append($deleteButton);
        $('.dyn-images').append($div);
    }

    function submitState() {
        var txtObj = document.getElementById("dyn-content");
        txtObj.value = trim(txtObj.value);
        if((uploadImg.length == 0) && (txtObj.value.length == 0)){
            return false;
        }
        if (txtObj.value.length > 0) {
            // var str = changetxt(txtObj.value);//替换文本框中的表情
            var formData = new FormData();
            formData.append("dynamicId", "[[${dynamic.dynamicId}]]");
            if (dynImage.length == 0) {
                formData.append("dynamicContent", JSON.stringify({'dynamicContent': txtObj.value}));
            }else{
                formData.append("dynamicContent", JSON.stringify({'dynamicContent': txtObj.value,'images':dynImage}));
            }
            if (uploadImg.length == 0){
                $.ajax({
                    url: '/dynamic/modifyDynamicInfoOnlyContent',
                    type: "post",
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        if (data["res"] == "success"){
                            swal("修改动态成功!", {
                                buttons: false,
                                timer: 2000
                            });
                            setTimeout(function () {
                                window.location.href = "/dynamic/homePage";
                            }, 1000);
                        }else if (data["res"] == "error"){
                            swal("错误", "修改动态失败！", "error");
                        }
                    },
                    error: function (data) {
                        swal("错误", "网络错误，请联系管理员！", "error");
                    }
                });
                return;
            }else{
                for (var f of uploadImg) {
                    formData.append("meFile", f);
                }
                $.ajax({
                    url: '/dynamic/modifyDynamicInfo',
                    type: "post",
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        if (data["res"] == "success"){
                            swal("修改动态成功!", {
                                buttons: false,
                                timer: 2000
                            });
                            setTimeout(function () {
                                window.location.href = "/dynamic/homePage";
                            }, 1000);
                        }else if (data["res"] == "error"){
                            swal("错误", "修改动态失败！", "error");
                        }
                    },
                    error: function (data) {
                        swal("错误", "网络错误，请联系管理员！", "error");
                    }
                });
            }
        }else{
            swal("警告", "需要配上文字描述才能发布哦", "warning");
        }
    }

    function returnHome(){
        swal({
            title: "取消编辑动态",
            text: "你确定要取消编辑该动态吗？",
            icon: "warning",
            buttons: true,
            dangerMode: true,
        }).then((willDelete) => {
            if (willDelete) {
                window.location.href = "/dynamic/homePage";
            }
        })
    }
</script>
</body>
</html>